package com.bankapp.network.bank;

import com.bankapp.domain.bank.Bank;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class BankServer {
    private ServerStub serverStub;

    public BankServer(ServerStub serverStub) {
        this.serverStub = serverStub;
    }

    public void startServer(Bank bank) {
        System.out.println("Begin listening port ");
        try (ServerSocket ss = new ServerSocket(ConnectionData.PORT);
             Socket s = ss.accept()) {
            ss.setSoTimeout(1000);
            SendData(bank, s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void SendData(Bank bank, Socket s) {
        try (DataOutputStream out = new DataOutputStream(s.getOutputStream());
             DataInputStream in = new DataInputStream(s.getInputStream())) {
            String inputMessage = in.readUTF();
            String outputMessage = serverStub.answer(inputMessage, bank);

            out.writeUTF(outputMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}